package com.itcam.cm.pay.controller;


import com.alipay.api.internal.util.AlipaySignature;
import com.itcam.cm.model.vo.common.Result;
import com.itcam.cm.pay.service.AlipayService;
import com.itcam.cm.pay.service.PaymentService;
import com.itcam.cm.pay.util.AliPublicKeysProperties;
import jakarta.servlet.http.HttpServletRequest;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RequestMapping("/api/order/alipay/")
@RestController
public class AlipayController {

    @Autowired
    AlipayService alipayService;

    @Autowired
    AliPublicKeysProperties aliPublicKeysProperties;

    @Autowired
    PaymentService paymentService;

    @GetMapping("submitAlipay/{orderNo}")
    public Result<String> submitAlipay(@PathVariable String orderNo){

        String form = alipayService.submitAlipay(orderNo);

        return Result.ok(form);
    }

    @SneakyThrows
    @PostMapping("notify")
    public String nofity(@RequestParam Map<String, String> paramMap,HttpServletRequest request){
        //String parameter = request.getParameter("");
        //Map<String, String[]> parameterMap = request.getParameterMap();
        // 生成公钥和私钥
        System.out.println(aliPublicKeysProperties.getPublicKey());// 阿里的公钥
        System.out.println(aliPublicKeysProperties.getAppId());// appId
        System.out.println(aliPublicKeysProperties.getPrivateKey());// 我们的私钥
        // 验签(验证签名)
        boolean rsa2 = AlipaySignature.rsaCheckV1(paramMap,aliPublicKeysProperties.getPublicKey(), "utf-8", "RSA2");

        if(rsa2){
            // 异步回调通知
            System.out.println("系统根据支付宝回调结果更新系统信息");
            paymentService.notifyPayment(paramMap,request);
        }

        return "success";
    }


}
